package edu.isquen.core.admin.dao;

import java.util.Collection;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import edu.isquen.core.admin.model.Superuser;
import edu.isquen.core.base.dao.BaseDAO;
import edu.isquen.core.base.dao.DataPackage;
import edu.isquen.core.base.model.ValueObject;
import edu.isquen.util.CommUtil;

public class SuperuserDAO extends BaseDAO<Superuser> implements ISuperuserDAO {

	public SuperuserDAO(String className) {
		super(className);
	}

	@SuppressWarnings("unchecked")
	public Superuser login(String loginno, String loginpwd) throws Exception {
		Session session = getSession();
		Superuser rtn = null;
		String hql = "FROM " + this.voClazzName + " WHERE loginno='" + loginno + "' and loginpwd='"+loginpwd+"'";
		Query query = session.createQuery(hql);
		query.setFirstResult(0);
		query.setMaxResults(1);
		List<Superuser> result = query.list();

		if (!result.isEmpty()) {
			rtn = (Superuser) result.get(0);
		}
		return rtn;
	}

	public ValueObject find(String id) {
		Session session = getSession();
		ValueObject rtn = null;
		if (id != null && id.length() > 0) {
			String hql = "FROM " + this.voClazzName + " WHERE id='" + id + "'";
			Query query = session.createQuery(hql);
			query.setFirstResult(0);
			query.setMaxResults(1);
			@SuppressWarnings("unchecked")
			List<ValueObject> result = query.list();

			if (!result.isEmpty()) {
				rtn = (ValueObject) result.get(0);
			}
		}
		return rtn;
	}

	public DataPackage<Superuser> findByAny(ValueObject obj) throws Exception {
		Superuser user = (Superuser) obj;
		String dql = "FROM " + this.voClazzName + " where 1=1";
		if (CommUtil.validateString(user.getId())) {
			dql += " and id='" + user.getId() + "'";
		}
		if (CommUtil.validateString(user.getLoginno())) {
			dql += " and loginno='" + user.getLoginno() + "'";
		}
		if (CommUtil.validateString(user.getLoginpwd())) {
			dql += " and loginpwd='" + user.getLoginpwd() + "'";
		}
		return getDatas(dql);
	}

	public Collection<Superuser> findAll(ValueObject obj) throws Exception {
		String hql = "FROM " + this.voClazzName;
		return getDatas(hql).datas;
	}

	public Collection<Superuser> findAllByPage(ValueObject obj, int page,
			int lines) throws Exception {
		String sql = "FROM " + this.voClazzName;
		return getDatas(sql, page, lines).datas;
	}
}
